package com.bailiban.user.service;

import com.bailiban.common.util.IdWorker;
import com.bailiban.user.entity.Admin;
import com.bailiban.user.mapper.AdminMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zhulang
 * @Classname AdminService
 * @Description AdminService
 */
@Service
public class AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder bCrypt;

    public Admin findById(String id) {
        return adminMapper.selectById(id);
    }

    public void add(Admin admin) {
        admin.setId(idWorker.nextId() + "");
        //将原始密码进行加密
        admin.setPassword(bCrypt.encode(admin.getPassword()));
        adminMapper.insert(admin);
    }

    public void delete(String id) {
        adminMapper.deleteById(id);
    }

    public Admin login(String loginname, String password) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loginname", loginname);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin != null && bCrypt.matches(password, admin.getPassword())) {
//    登录成功
            return admin;
        }
        return null;
    }
}
